// wxWidgets frontend

#include <wx/wx.h>
#include <iostream>

#include "Calc.h"

class MyApp : public wxApp
{
    virtual bool OnInit();
};

IMPLEMENT_APP(MyApp)


class CalcFrame : public wxFrame
{
	wxPanel *root;
	wxFlexGridSizer *rootSizer;
	wxTextCtrl *messages;
	wxTextCtrl *input;

	Calc calc;
public:
    CalcFrame(const wxString& title, const wxPoint& pos, const wxSize& size);
    void OnQuit(wxCommandEvent& event);
    void OnAbout(wxCommandEvent& event);
    void OnInputEnter(wxCommandEvent& event);
};

enum
{
    ID_Quit=1,
    ID_About,
	ID_Input
};


bool MyApp::OnInit()
{
    CalcFrame *frame = new CalcFrame( _("OpenTransCalc"), wxPoint(50, 50),
                                  wxSize(450, 350));

    frame->Show(true);
    SetTopWindow(frame);
    return true;
}

CalcFrame::CalcFrame(const wxString& title, const wxPoint& pos, const wxSize& size)
    : wxFrame( NULL, -1, title, pos, size )
{
	rootSizer = new wxFlexGridSizer(2, 1, 0, 1);

	root = new wxPanel(this, wxID_ANY);
	input = new wxTextCtrl(root, ID_Input, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_PROCESS_ENTER);
	messages = new wxTextCtrl(root, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_MULTILINE|wxTE_READONLY);

	rootSizer->Add(messages, 1, wxEXPAND);
	rootSizer->Add(input, 1, wxEXPAND);

	rootSizer->AddGrowableRow(0);
	rootSizer->AddGrowableCol(0);

	root->SetSizer(rootSizer);

	wxMenuBar *menuBar = new wxMenuBar;

    wxMenu *menuFile = new wxMenu;

    menuFile->Append( ID_About, _("&About...") );
    menuFile->AppendSeparator();
    menuFile->Append( ID_Quit, _("E&xit") );

    menuBar->Append(menuFile, _("&File") );

    SetMenuBar(menuBar);

	Connect(ID_Input, wxEVT_COMMAND_TEXT_ENTER,
		(wxObjectEventFunction) &CalcFrame::OnInputEnter);
    Connect(ID_Quit, wxEVT_COMMAND_MENU_SELECTED,
		(wxObjectEventFunction) &CalcFrame::OnQuit);
    Connect(ID_About, wxEVT_COMMAND_MENU_SELECTED,
		(wxObjectEventFunction) &CalcFrame::OnAbout);
}

void CalcFrame::OnQuit(wxCommandEvent& WXUNUSED(event))
{
    Close(true);
}

void CalcFrame::OnAbout(wxCommandEvent& WXUNUSED(event))
{
    wxMessageBox( _("OpenTransCalc v0.1\n\nA smart calculator"), 
                  _("About OpenTranscalc"),
                  wxOK|wxICON_INFORMATION, this );
}

void CalcFrame::OnInputEnter(wxCommandEvent& WXUNUSED(event))
{
	StringRef expr = StringRef::acquire(utf8dup(input->GetValue()));
	StringRef result = calc.calculate(expr);
	AutoDeleteArray<wchar_t> buf = new wchar_t[result.getLength()+1];
	utf8cpy(buf, result.getLength()+1, *result);
	*messages << wxString(buf) << L'\n';
	input->ChangeValue(L"");
}
